import os

from homes.models import House, Area

os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE',
    'ihome.settings'
)
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from django.shortcuts import render
from django.utils.decorators import method_decorator
from ihome.utils.views import login_required, QiniuUpload
from django.views import View
from django.http import JsonResponse, HttpResponse
from users.models import User
from .models import User
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
import json
import re
import datetime
from django.conf import settings
from qiniu import Auth, put_file, etag
import qiniu.config


# Create your views here.


# 用户注册
class RegisterView(View):

    def post(self, request):
        # 1、提取参数
        data = json.loads(request.body.decode())
        password = data.get('password')
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')

        # 2、校验参数
        if not all([password, mobile, phonecode]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少参数'}, status=400)

        if not re.match(r"^1[35678]\d{9}$", mobile):
            return JsonResponse({'errno': 4103, 'errmsg': '手机号有误'}, status=400)

        if not re.match(r'^\w{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': '密码格式有误'}, status=400)

        if not re.match(r'^\d{6}$', phonecode):
            return JsonResponse({'errno': 4103, 'errmsg': '手机验证码格式有误'}, status=400)

        # 手机验证码校验
        conn = get_redis_connection('sms_code')
        sms_code_from_redis = conn.get('sms_%s' % mobile)
        if not sms_code_from_redis:
            return JsonResponse({'errno': 4004, 'errmsg': '短信验证码过期！'}, status=400)
        sms_code_from_redis = sms_code_from_redis.decode()
        if sms_code_from_redis != phonecode:
            return JsonResponse({'errno': 4004, 'errmsg': '短信验证码有误！'}, status=400)

        # 3、新建数据,构建用户模型类对象保存数据库
        try:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile,
            )
        except Exception as e:
            print(e)

        # 状态保持
        login(request, user)

        response = JsonResponse({'errno': 0,
                             'errmsg': ' ok',
                             'data': {
                                 "name": user.username,
                                 'user_id': user.id
                             }

                             })

        # response.set_cookie('username', user.username, max_age= 3600* 24 *14)

        # 4、构建响应
        return response


# 用户登录
# 传统登陆(校验用户名和密码)
class LoginView(View):

    def post(self, request):
        # 1、提取参数
        data = json.loads(request.body.decode())
        username = data.get('mobile')
        password = data.get('password')

        # 2、校验参数
        if not all([username, password]):
            return JsonResponse({'errno': 4103, 'errmsg': '参数缺失！'})

        if not re.match(r'^\w{5,20}$', username):
            return JsonResponse({'errno': 4103, 'errmsg': '用户名格式有误'}, status=400)

        if not re.match(r'^\w{8,20}$', password):
            return JsonResponse({'errno': 4103, 'errmsg': '密码格式有误'}, status=400)

        user = authenticate(request, username=username, password=password)
        if not user:
            return JsonResponse({"errno": 4102, 'errmsg': '您提供的身份信息无法验证！'}, status=401)

        # 状态保持
        login(request, user)

        # 4、构建响应
        response = JsonResponse({'errno': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age= 3600* 24 *14)

        return response

    # 用户退出
    @method_decorator(login_required)
    def delete(self, request):
        # 1.获取用户对象
        user = request.user
        # 2.调用logout函数清除用户session数据
        logout(request)

        # 3.构建响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('name')

        return response

    # 判断是否登录
    def get(self, request):
        # 1.获取用户对象
        user = request.user

        if user.is_authenticated:
            return JsonResponse({
                'errmsg': '已登录',
                'errno': 0,
                'data': {"name": user.username,
                         'user_id': user.id}

            })
        # 2.构建并返回相应数据
        return JsonResponse({'errno': 4101, 'errmsg': '未登录', })


# 个人中心
class UserInfoView(View):

    @method_decorator(login_required)
    def get(self, request):
        # 1.获取用户对象
        user = request.user

        info_data = {
            "avatar_url": 'http://qetqu0w54.bkt.clouddn.com/' + str(user.avatar),
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id

        }
        # 2.构建并返回相应数据
        return JsonResponse({
            'errmsg': 'ok',
            'errno': 0,
            'data': info_data
        })


# 用户名修改
class UpdateUsername(View):

    # 修改用户名
    @method_decorator(login_required)
    def put(self, request):

        user = request.user

        # 提取参数
        data = json.loads(request.body.decode())
        name = data.get('name')
        count = User.objects.filter(username=name).count()

        if not name:
            return JsonResponse({'errno': 40103, 'errmsg': '缺少参数'})

        if not re.match(r'\w{2,20}$', name):
            return JsonResponse({'errno': 4103, 'errmsg': '用户名格式错误'})

        if count >= 1:
            return JsonResponse({'errno': 4003, 'errmsg': '用户名已存在'})

        try:
            user.username = name
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4004, 'errmsg': '修改用户名失败'})

        return JsonResponse({'errno': 0, 'errmsg': '修改成功'})


# 头像上传修改
class UserAvatar(View):

    # 上传个人头像
    @method_decorator(login_required)
    def post(self, request):
        # 提取参数
        user = request.user
        user_id = str(user.id)

        # 获取上传的图片对象
        imge_data = request.FILES.get('avatar')

        '''
        图片对象属性
        image_data = [avatar.file, avatar.field_name, avatar.name, avatar.content_type,
                      avatar.size, avatar.charset, avatar.content_type_extra]
        '''

        data = imge_data.file.read()

        # 构造文件名
        file_name = user_id + datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        # 把文件写入到本地服务器中
        with open('ihome/uploads/'+file_name, 'wb') as f:
            f.write(data)


        # 拼接上传目标文件路径
        avatar_file = settings.BASE_DIR + '/ihome/uploads/' + file_name
        # print(avatar_file)
        # print(avatar_file)

        avatar = QiniuUpload(user_id, avatar_file)

        # 删除上传到本地的临时文件
        os.remove(settings.BASE_DIR + '/ihome/uploads/' + file_name)
        try:
            user.avatar = avatar
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4302, 'errmsg': '上传头像失败'})


        # 构建响应数据
        avatar_url = settings.QINIU_URL + avatar
        return JsonResponse({
            'errno': 0,
            'errmsg': '上传头像成功',
            'data':{'avatar_url': avatar_url}
        })


# 用户实名认证
class UserAuth(View):

    # 实名认证
    @method_decorator(login_required)
    def post(self, request):

        # 提取参数
        data = json.loads(request.body.decode())

        real_name = data.get('real_name')

        id_card = data.get('id_card')

        if real_name:
            if not re.match(r'^([\u4e00-\u9fa5]{1,20}|[a-zA-Z\.\s]{1,20})$', real_name):
                return JsonResponse({'errno': 4103, 'errmsg': '参数real_name有误'})
        if id_card:
            if not re.match(r'(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)', id_card):
                return JsonResponse({'errno': 40103, 'errrmsg': '参数id_card有误'})

        # 创建用户对象
        user = request.user

        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4004, 'errmsg': '认证信息保存失败'})

        return JsonResponse({'errno': 0, 'errmsg': '认证信息保存成功'})

    # 认证信息展示
    @method_decorator(login_required)
    def get(self, request):

        # data = json.loads(request.body.decode())

        user = request.user

        real_name = user.real_name
        id_card = user.id_card

        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4105, 'errmsg': '用户未认证'})

        return JsonResponse({'errno': '0',
                             'errmsg': 'ok',
                             'data': {
                                 'real_name': real_name,
                                 'id_card': id_card
                             }
                             })


# 我的房屋列表
class MyHouse(View):


    # 我的房屋列表展示
    @method_decorator(login_required)
    def get(self, request):

        # 定义房屋空列表
        houses_list = []

        user = request.user

        houses = House.objects.filter(user_id=user.id).order_by('-create_time')



        for house in houses:
            areas = Area.objects.filter(id=house.area_id)

            for area in areas:
                houses_list.append({
                    'address': house.address,
                    'area_name':  area.name,
                    'ctime': house.create_time,
                    'house_id': house.id,
                    "img_url": settings.QINIU_URL + house.index_image_url,
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": settings.QINIU_URL + str(user.avatar)
                })


        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data' : {
                'houses': houses_list
            }
        })
